import React, { useEffect, useState } from "react";
import { Button, message } from "antd";
import { RedoOutlined } from "@ant-design/icons";

const ThrottleButton = ({onClick, title, interval = 200}: any) => {
  const [lastTime, setLastTime] = useState(interval);

  const throttle = function<T extends (...args: any[]) => void>(func: T): T {
    return function(this: any, ...args: any[]) {
      if (lastTime > 0) {
        message.warning('刷新频率太高，请拨打完所有电话再刷新此列表');       
      } else {
        func.apply(this, args);
        setLastTime(interval);
      }
    } as T;
  };

  useEffect(() => {
    if (lastTime >= 0) {
      setTimeout(() => {
        setLastTime(lastTime - 1);
      }, 1000)
    } 
  }, [lastTime]);


  const handleReloadThrottle = throttle(onClick)

  return <Button type="default" disabled={lastTime > 0} onClick={handleReloadThrottle}><RedoOutlined />{lastTime > 0 ? ` 刷新倒计时(${lastTime})` : title}</Button>;
}

export default ThrottleButton;